package com.tlkj.common.curd.controller.admin;

import com.github.pagehelper.Page;
import com.tlkj.common.curd.entity.Api;
import com.tlkj.common.curd.entity.BaseEntity;
import com.tlkj.common.curd.entity.BaseEntity.Save;
import com.tlkj.common.curd.interceptor.ApiInterfaceInterceptor;
import com.tlkj.common.curd.model.AjaxResult;
import com.tlkj.common.curd.service.ApiService;
import com.tlkj.common.curd.util.DynamicSqlFieldExtractor;
import com.tlkj.common.curd.util.MyBatisSqlRegexExtractor;
import com.tlkj.common.curd.vo.ApiVo;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.sql.SQLException;
import java.util.Map;

/**
 * API - Controller
 * @author flyong86
 * @since 2024年6月19日
 */
@Slf4j
@RequiredArgsConstructor
@RequestMapping("/admin/common/curd/api")
@RestController
public class AdminApiController {

    private final ApiService apiService;
    private final DynamicSqlFieldExtractor dynamicSqlFieldExtractor;
    private final ApiInterfaceInterceptor apiInterfaceInterceptor;

    @GetMapping("/list")
    public AjaxResult list(Page<Api> page, ApiVo api)  {
        return AjaxResult.success(apiService.page(page, api));
    }

    @GetMapping("/detail/{id}")
    private AjaxResult detail(@PathVariable("id") String id) {
        return AjaxResult.success(apiService.findInfo(id));
    }

    @PostMapping("/save")
    public AjaxResult save(@RequestBody @Validated(Save.class) ApiVo api) {
        try {
            apiService.save(api);
        } catch (Exception e) {
            log.error("保存API异常!", e);
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success(api);
    }

    @PostMapping("/update")
    public AjaxResult update(@RequestBody @Validated(BaseEntity.Update.class) ApiVo api) {

        try {
            apiService.update(api);
        } catch (Exception e) {
            log.error("更新API异常!", e);
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success(api);
    }

    @GetMapping("/delete/{id}")
    public AjaxResult delete(@PathVariable("id") String id) {
        try {
            apiService.deleteById(id);
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
        return AjaxResult.success();
    }

    /**
     * 获取请求参数.
     * @param params SQL脚本
     * @return 请求参数列表
     * @throws Exception
     */
    @PostMapping("/analyzeRequestParams")
    public AjaxResult analyzeRequestParams(@RequestBody Map<String, Object> params) {
        if (!params.containsKey("script")) {
            return AjaxResult.error("script不能为空!");
        }

        return AjaxResult.success(MyBatisSqlRegexExtractor.extractParameters(params.get("script").toString()));
    }

    /**
     * 分析返回参数.
     * @param params 参数
     * @return 参数列表
     * @throws SQLException
     */
    @PostMapping("/analyzeReturnParams")
    public AjaxResult analyzeReturnParams(@RequestBody Map<String, Object> params) throws Exception {
        if (!params.containsKey("script")) {
            return AjaxResult.error("script不能为空!");
        }

        try {
            String script = params.remove("script").toString();
            return AjaxResult.success(dynamicSqlFieldExtractor.getDynamicSqlField(script, params));
        } catch (Exception e) {
            log.error("分析返回参数异常!", e);
            return AjaxResult.error(e.getMessage());
        }
    }

    @PostMapping("/test")
    public Object test(@RequestBody @Validated(Save.class) ApiVo api) {
        return apiInterfaceInterceptor.executeDynamicScript(api, api.getTestParams(), false, null);
    }
}
